package com.msb.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.msb.common.constant.ProductConstant;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;
import com.msb.mall.product.dao.AttrAttrgroupRelationDao;
import com.msb.mall.product.dao.AttrGroupDao;
import com.msb.mall.product.entity.AttrAttrgroupRelationEntity;
import com.msb.mall.product.entity.AttrGroupEntity;
import com.msb.mall.product.entity.CategoryEntity;
import com.msb.mall.product.service.AttrAttrgroupRelationService;
import com.msb.mall.product.service.CategoryService;
import com.msb.mall.product.vo.AttrGroupRelationVo;
import com.msb.mall.product.vo.AttrResponseVo;
import com.msb.mall.product.vo.AttrVo;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.msb.mall.product.dao.AttrDao;
import com.msb.mall.product.entity.AttrEntity;
import com.msb.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存, 保存属性同时保存关联表信息（属性与属性组关联）
     */
    @Transactional
    @Override
    public void saveDetail(AttrVo attr){
        // 1.保存正常属性信息
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr,entity);
        this.save(entity);
        // 2.保存属性组关联信息
        if (null != attr.getAttrGroupId() && 0 != attr.getAttrGroupId()){
            AttrAttrgroupRelationEntity aare = new AttrAttrgroupRelationEntity();
            aare.setAttrGroupId(attr.getAttrGroupId());
            aare.setAttrId(entity.getAttrId());

            attrAttrgroupRelationService.save(aare);
        }
    }

    /**
     * 获取详情列表
     * @param params
     * @param cateId
     * @return
     */
    @Override
    public PageUtils queryPageDetail(Map<String, Object> params,String type, Long cateId) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type","base".equalsIgnoreCase(type)?1:0);
        // 1.根据类别编号查询
        if (cateId != 0){
            wrapper.eq("catelog_id",cateId);
        }
        // 2.key模糊查询
        String key = (String) params.get("key");
        if (!StringUtils.isNullOrEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).like("attr_name",key);
            });
        }
        // 3.分页查询
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        // 4. 关联查询出类别名称和属性组名称
        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVo> list = records.stream().map((m)->{
            AttrResponseVo responseVo = new AttrResponseVo();
            BeanUtils.copyProperties(m,responseVo);
            // 每一条规格对应的类别
            CategoryEntity categoryEntity = categoryService.getById(m.getCatelogId());
            if (categoryEntity.getName() != null)
            responseVo.setCatelogName(categoryEntity.getName());
            if ("base".equals(type)){
                // 每一条规格对应的属性组
                AttrAttrgroupRelationEntity aare = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", m.getAttrId())
                );
                if (aare != null && aare.getAttrGroupId() != null){
                    AttrGroupEntity age = attrGroupDao.selectById(aare.getAttrGroupId());
                    if (age.getAttrGroupName() != null)
                        responseVo.setGroupName(age.getAttrGroupName());
                }
            }

            return responseVo;
                }
        ).collect(Collectors.toList());
        pageUtils.setList(list);
        return pageUtils;
    }

    @Override
    public AttrResponseVo getAttrInfo(Long attrId) {
        AttrResponseVo responseVo = new AttrResponseVo();
        AttrEntity byId = this.getById(attrId);
        BeanUtils.copyProperties(byId,responseVo);
        if (byId.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            // 查询属性组信息
            AttrAttrgroupRelationEntity aare = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrId)
            );
            if (aare != null && aare.getAttrGroupId() != null){
                AttrGroupEntity age = attrGroupDao.selectById(aare.getAttrGroupId());
                if (age.getAttrGroupName() != null)
                    responseVo.setGroupName(age.getAttrGroupName());
                responseVo.setAttrGroupId(age.getAttrGroupId());
            }
        }

        // 查询类别信息
        Long[] catelogPath = categoryService.findCatelogPath(responseVo.getCatelogId());
        responseVo.setCatelogPath(catelogPath);
        // 类别名称
        CategoryEntity cate = categoryService.getById(responseVo.getCatelogId());
        responseVo.setCatelogName(cate.getName());

        return responseVo;
    }

    /**
     * 修改类别详情，关联表更新
     * @param attr
     */
    @Override
    public void updateAttrInfo(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 修改属性组关联表信息信息
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            entity.setAttrId(attr.getAttrId());
            entity.setAttrGroupId(attr.getAttrGroupId());
            AttrAttrgroupRelationEntity one = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (one != null) {
                attrAttrgroupRelationService.update(entity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));

            } else {
                attrAttrgroupRelationService.save(entity);
            }
        }
    }

    /**
     * 删除 操作
     * @param asList
     */
    @Override
    public void removeDetailsByIds(List<Long> asList) {
        // 删除属性组关联表信息
        for (Long one : asList) {
            AttrEntity entity = this.getById(one);
            if (entity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
                attrAttrgroupRelationService.remove(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",entity.getAttrId()));
            }
        }
        this.removeByIds(asList);
    }

    /**
     * 查询属性组关联的属性信息
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getAttrRelation(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> attrGroupList =
                attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<AttrEntity> attrList = attrGroupList.stream().map((one) -> this.getById(one.getAttrId())).collect(Collectors.toList());

        return attrList;
    }

    /**
     * 移除属性组与基本属性关联关系
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrAttrgroupRelationEntity> list = Stream.of(vos).map((item) -> {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, entity);
            return entity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.removeBatchRelation(list);
    }

    /**
     * 查询未关联属性
     * @param attrGroupId
     * @return
     */
    @Override
    public PageUtils selectNoattrRelation(Long attrGroupId,Map<String, Object> params) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        // 1.查询当前分组信息
        AttrGroupEntity attrGroup = attrGroupDao.selectById(attrGroupId);
        // 获取分组类别id
        Long catelogId = attrGroup.getCatelogId();
        // 获取当前类别下的所有分组id
        List<AttrGroupEntity> attrGroupList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupIdList = attrGroupList.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());
        // 然后查询出当前类别下所有已经关联的基本属性id
        List<AttrAttrgroupRelationEntity> aareList = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIdList));
        List<Long> attrIds = aareList.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        // 查询当前类别下的所有的基本属性
        wrapper.eq("catelog_id",catelogId)
                .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (null != attrIds && attrIds.size()>0){
            wrapper.notIn("attr_id",attrIds);
        }
        // 模糊分页擦查询
        String key = (String) params.get("key");
        if (!StringUtils.isNullOrEmpty(key)){
            wrapper.and(w->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        // 分页
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

}